<template>
	<div style="display:flex; justify-content: center;">
		<el-space id="auth-form" direction="vertical" :size=10>
			<h2 id="auth-title">{{ isLogin ? '登录' : '注册' }}</h2>
			<el-input v-model="username" style="width: 15vw;" placeholder="请输入用户名" />
			<el-input v-model="password" style="width: 15vw;" type="password" placeholder="请输入密码" show-password />
			<el-space v-if="!isLogin" direction="vertical" :size=10>
				<el-input v-model="confirmPassword" style="width: 15vw;" type="password" placeholder="请确认密码"
					show-password />
				<div style="display: flex; align-items: center; width: 15vw;">
					<el-input v-model="email" style="width: 70%;" placeholder="请输入邮箱" />
					<el-button style="width: 30%; margin-left: 1vw;" type="primary" plain @click="sendEmailCode"
						:disabled="isSendingEmailCode">
						{{ isSendingEmailCode ? '重新发送(' + countdown + 's)' : '发送验证码' }}
					</el-button>
				</div>
				<el-input v-model="emailCode" style="width: 15vw;" placeholder="请输入邮箱验证码" />
			</el-space>

			<el-button style="width: 15vw;" type="primary" plain @click="isLogin ? login() : register()">
				{{ isLogin ? '登录' : '注册' }}
			</el-button>
			<el-button style="width: 15vw; margin-bottom: 1vh;" type="primary" link @click="toggleAuthMode">
				{{ isLogin ? '切换到注册' : '切换到登录' }}
			</el-button>
		</el-space>
	</div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import axios from 'axios'
import { updateAuth, UpdateAuthParams } from '../utils/tokenAxiosUtils';
import { UserLoginSuccessDto } from '@/types/userType';
import { saveUserInfo } from '@/utils/persistUtils';

// 定义两个不同的响应式引用，分别用于用户名和密码
const username = ref('')
const password = ref('')
const confirmPassword = ref('')
const email = ref('')
const emailCode = ref('')
const isLogin = ref(true) // 默认显示登录界面
const isSendingEmailCode = ref(false) // 是否正在发送验证码
const countdown = ref(60) // 倒计时时间

// 监听 username 和 password 的变化
watch([username, password], ([newUsername, newPassword]) => {
	// 使用正则表达式替换非字母和数字的字符为空字符串
	// username.value = newUsername.replace(/[^A-Za-z0-9]/g, '')
	password.value = newPassword.replace(/[^A-Za-z0-9]/g, '')
})

// 监听 confirmPassword 的变化
watch(confirmPassword, (newConfirmPassword) => {
	// 使用正则表达式替换非字母和数字的字符为空字符串
	confirmPassword.value = newConfirmPassword.replace(/[^A-Za-z0-9]/g, '')
})

// 定义验证邮箱格式的方法
const validateEmail = (email: string) => {
	const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
	return emailRegex.test(email);
}

// 定义验证密码一致性的方法
const validatePasswords = (password: string, confirmPassword: string) => {
	return password === confirmPassword;
}

// 定义登录方法
const login = async () => {
	if (!username.value || !password.value) {
		window.alert('用户名和密码不能为空！')
		return
	}

	try {
		const response = await axios.post('/api/user/login', {
			email: username.value,
			password: password.value
		})
		// 处理登录成功的逻辑
		console.log(response.data);
		window.alert('登录成功！')
		var res = response.data as UserLoginSuccessDto;
		const { accessToken, refreshToken, expiresIn } = res.tokens;
		updateAuth({ accessToken, refreshToken, expiresIn: Number(expiresIn) });
		saveUserInfo(res);
	} catch (error) {
		// 处理登录失败的逻辑
		console.error(error.code)
		window.alert('登录失败！ ')
	}
}

// 定义注册方法
const register = async () => {
	if (!username.value || !password.value || !email.value || !emailCode.value || !confirmPassword.value) {
		window.alert('用户名、密码、邮箱、验证码和确认密码不能为空！')
		return
	}

	if (!validatePasswords(password.value, confirmPassword.value)) {
		window.alert('两次输入的密码不一致，请重新输入！')
		return
	}

	try {
		const response = await axios.post('/api/user/register', {
			username: username.value,
			password: password.value,
			email: email.value,
			verificationCode: emailCode.value
		})
		// 处理注册成功的逻辑
		console.log(response.data)
		window.alert('注册成功！')
		isLogin.value = true // 注册成功后切换到登录界面
	} catch (error) {
		// 处理注册失败的逻辑
		console.error('注册失败', error.code)
		window.alert('注册失败！ ')
	}
}

// 定义发送邮箱验证码方法
const sendEmailCode = async () => {
	if (!email.value) {
		window.alert('请输入邮箱地址！')
		return
	}

	if (!validateEmail(email.value)) {
		alert('请输入有效的邮箱地址')
		email.value = '';
		return;
	}

	if (isSendingEmailCode.value) {
		return
	}

	try {
		isSendingEmailCode.value = true
		const response = await axios.post('/api/verificationCode/send', null, {
			params: {
				email: email.value
			}
		})
		// 处理发送验证码成功的逻辑
		console.log(response.data)
		startCountdown()
	} catch (error) {
		// 处理发送验证码失败的逻辑
		console.error('发送验证码失败', error)
		window.alert('发送验证码失败！')
		isSendingEmailCode.value = false // 发送失败时重置状态
	}
}

// 启动倒计时
const startCountdown = () => {
	countdown.value = 60
	const timer = setInterval(() => {
		countdown.value--
		if (countdown.value <= 0) {
			clearInterval(timer)
			isSendingEmailCode.value = false
		}
	}, 1000)
}

// 切换登录和注册模式
const toggleAuthMode = () => {
	isLogin.value = !isLogin.value
}
</script>

<style scoped>
#auth-form {
	width: 20vw;
	margin-top: 20vh;
	background-color: #b0e6bd;
	border-radius: 1rem;
}

#auth-title {
	color: #FFFFFF;
	height: 2vh;
}
</style>
